package com.frxuexi.sign.view

import android.text.TextUtils
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.navigation.NavHostController
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.HttpType
import com.frxuexi.lib_base.UiState
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.timerTask


lateinit var mapView: MapView
lateinit var map:BaiduMap
lateinit var mLocationClient:LocationClient
lateinit var timer: Timer
@Composable
fun SignCommitPage(navHostController: NavHostController,vm:SignViewModel= hiltViewModel()) {
    initMap()
    var startTime by remember {
        mutableStateOf("上班还未打卡")
    }
    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }
    var btnName by remember {
        mutableStateOf("上班打卡")
    }
    var nowTime by remember {
        mutableStateOf("00:00:00")
    }
    var enable by remember {
        mutableStateOf(true)
    }
    val kv = MMKV.defaultMMKV()

    val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_STOP -> {
                    // Do something when the component is stopped
                    println("Component Stopped")
                }

                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("打卡成功")
                    }

                    else -> {}
                }
            }
        }

        launch {
            timer= Timer()
            timer.schedule(timerTask {
                nowTime=SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            },0,1000)
        }

        launch {
            //取出上班打卡时间
            val signTime = kv.decodeString("sign", "").toString()
            //如果上班打卡不为空，说明打过
            if(!TextUtils.isEmpty(signTime)){
                //现在的日期
                val time =
                    SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                val signDate = signTime.substring(0, 10)
                //如果上班打卡日期是今天
                if(time==signDate){
                    //说明今天上班打过，显示上班打卡时间
                    startTime="上班时间：$signTime"
                    //取出下班打卡时间
                    val soutTime = kv.decodeString("sout")
                    val soutDate = soutTime?.substring(0, 10)
                    //如果下班打卡日期是今天
                    if(time==soutDate){
                        //说明今天下班打过，显示下班打卡时间
                        endTime="下班时间：$soutTime"
                        //按钮不可用
                        enable=false
                    }else{//如果下班打卡日期不是今天
                        btnName="下班打卡"
                    }
                }
            }
        }
    })

    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(10.dp)) {
        BaseTitle(title = "打卡", navHostController = navHostController)
        AndroidView(modifier=Modifier.height(300.dp),factory = {
            mapView=MapView(it)
            map = mapView.map
            map.setMyLocationEnabled(true)
            mapView
        })
        Spacer(modifier = Modifier.height(50.dp))
        Text(text = startTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp))
        Spacer(modifier = Modifier.height(20.dp))
        Text(text = endTime,
            Modifier
                .fillMaxWidth()
                .padding(start = 20.dp))
        Spacer(modifier = Modifier.height(20.dp))
        Button(modifier = Modifier
            .size(140.dp)
            .clip(CircleShape), enabled = enable, onClick = {
            val currentTimeMillis = System.currentTimeMillis()
            val map = mutableMapOf<String, Any>()
            map["userId"]=1
            map["SignLat"]=kv.decodeDouble("latitude")
            map["SignLong"]=kv.decodeDouble("longitude")
            map["signTime"]=currentTimeMillis
            val time =SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTimeMillis)
                if(btnName=="上班打卡"){
                    kv.encode("sign",time)
                    startTime="上班时间：$time"
                    btnName="下班打卡"
                    vm.sendIntent(SignIntent.sign(map))
                }else{
                    kv.encode("sout",time)
                    endTime="下班时间：$time"
                    vm.sendIntent(SignIntent.sout(map))
                    enable=false
                }
        }) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }
    }
}

fun initMap(){
    SDKInitializer.setAgreePrivacy(BaseApp.context, true)
    LocationClient.setAgreePrivacy(true)
    //定位初始化
    //定位初始化
    mLocationClient = LocationClient(BaseApp.context)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps

    option.setCoorType("bd09ll") // 设置坐标类型

    option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
    mLocationClient.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
    val myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
    mLocationClient.start()
}

class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mapView == null) {
            return
        }

        val latitude = location.latitude
        val longitude = location.longitude
        val kv = MMKV.defaultMMKV()
        kv.encode("latitude",latitude)
        kv.encode("longitude",longitude)

        //定位蓝点额外加的
        var ll = LatLng(latitude, longitude);
        val update = MapStatusUpdateFactory.newLatLngZoom(ll, 15f);
        map.animateMapStatus(update);

        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        map.setMyLocationData(locData)
    }
}